#include <iostream>
#include <thread>
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include <mutex>
#include <chrono>

using namespace std;
int fd = open("/dev/ttyACM0", O_RDWR | O_TRUNC);
mutex s_lock;

void serial_write(int x)
{
    for (int i = 0; i <= 10; i++)
    {
        size_t h = 10;
        char a[20] = "adsfasdfdsf";
        s_lock.lock();
        int w = write(fd, &a, h);
        s_lock.unlock();
        cout << "write:" << a << endl;
        cout << "write bytes:" << w << endl;
        this_thread::sleep_for(std::chrono::milliseconds(1000));
        
    }
}

void serial_read(int y)
{
    for (int i = 0; i <= 10; i++)
    {
        char a[13];
        size_t l = 20;
        int r = read(fd, &a, 20);
        cout << "recieve:" << a << endl;
        cout << "recieve bytes:" << r << endl;
        this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

int main()
{
    struct termios serialportsettings;
    if (fd == -1)
    {
        std::cout << "error";
        return 0;
    }
    else
    {
        std::cout << "sucessfully open a serialport" << endl;
    }

    tcgetattr(fd, &serialportsettings);
    serialportsettings.c_cflag &= PARENB;
    serialportsettings.c_cflag |= CREAD | CLOCAL;
    serialportsettings.c_cc[VMIN] = 10;
    serialportsettings.c_cc[VTIME] = 0;
    tcsetattr(fd, TCSANOW, &serialportsettings);

    std::thread t(serial_write, fd);
    std::thread r(serial_read, fd);

    t.join();
    r.join();

    close(fd);
    return 0;
}